package com.dpp.controller.user;

import cn.hutool.extra.qrcode.QrCodeUtil;
import cn.hutool.extra.qrcode.QrConfig;
import com.dpp.context.BaseContext;
import com.dpp.entity.AddressBook;
import com.dpp.entity.CouponImg;
import com.dpp.mapper.AddressMapper;
import com.dpp.mapper.CouponImgMapper;
import com.dpp.properties.JwtProperties;
import com.dpp.result.Result;
import com.dpp.service.ActivityService;
import com.dpp.service.CouponBookService;
import com.dpp.service.CouponImgService;
import com.dpp.service.UserService;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.UUID;

@RestController
@CrossOrigin
@RequestMapping("/user/coupon")
public class CouponController {
    @Autowired
    private AddressMapper addressMapper;
    @Autowired
    private CouponImgMapper couponImgMapper;
    @Autowired
    private ActivityService activityService;
    @Autowired
    private CouponImgService couponImgService;
    @Autowired
    private UserService userService;
    @Autowired
    private JwtProperties jwtProperties;
    @GetMapping("/get")
    public Result get(){
        String openid = BaseContext.getCurrentId();
        return   activityService.getCoupon(openid);
    }
    @GetMapping("/get2")
    public Result get2(){
        String openid = BaseContext.getCurrentId();
        return   activityService.getCouponById2(openid);
    }
    @GetMapping("/getImg")
    public Result getImg(HttpServletResponse response) throws IOException {
        String openid = BaseContext.getCurrentId();
        if(!openid.equals("oD1dE6RdILU9O-EXNaaOSc4cK2-g"))
        {
            return Result.error("权限不足");
        }
        String uuid=couponImgService.CheckImg();
        QrConfig config = new QrConfig(500, 500);
        // 设置边距，既二维码和背景之间的边距
        config.setMargin(1);
        // 设置前景色，二维码颜色（绿色）
        config.setForeColor(new Color(0, 0, 0));
        // 设置背景色（淡黄色）
        config.setBackColor(new Color(255, 255, 255));
        // 设置中间的 logo 图片
        String logoPath = ResourceUtils.getFile(jwtProperties.getImgPath()).getPath();
        config.setImg(logoPath);
        // 设置容错级别
        config.setErrorCorrection(ErrorCorrectionLevel.H);
        String url = jwtProperties.getUrl();
        String[] parts = url.split("://");
        url=parts[1];
        // 生成二维码到文件，也可以到流
        byte[] pngArr = QrCodeUtil.generatePng("https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx576478355cd34bb0&redirect_uri="+parts[0]+"%3A%2F%2F"+url+"%2Fuser%2Fcoupon%2Fcheckcoupon?id="+uuid+"&response_type=code&scope=snsapi_userinfo&state=1&connect_redirect=1#wechat_redirect", config);
        return Result.success(pngArr);
    }
    @GetMapping("/checkcoupon")
    public void checkcoupon(String id,String code, HttpServletResponse resp) throws IOException {
        String openid = userService.getOpenid(code);
        Integer check = couponImgService.getCoupon(id,openid);
        if(check.equals(0))
        {
            CouponImg couponImg = couponImgMapper.selectByUrlId(id);
            AddressBook addressBook = addressMapper.selectByOpenid(couponImg.getOpenid());
            String address = addressBook.getAddress().substring(0, addressBook.getAddress().lastIndexOf("/") + 1);
            String phone = addressBook.getPhone().substring(addressBook.getPhone().length() - 4);
            String url = jwtProperties.getUrl().concat("/personalCenter.html?popup="+check+"&phone="+phone+"&address="+ URLEncoder.encode(address, "UTF-8"));
            resp.sendRedirect(url);
            return;

        }
        String url = jwtProperties.getUrl().concat("/personalCenter.html?popup="+check);
        resp.sendRedirect(url);
    }

}
